package com.firmye.auth.config.oauth2;

import com.firmye.auth.config.security.CustomUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;

import javax.sql.DataSource;

/**
 * 授权端点：/oauth/authorize?client_id=client_id&response_type=code&redirect_uri=redirect_uri
 * 令牌端点：/oauth/token
 * 用户确认授权提交端点：/oauth/confirm_access
 * 授权错误信息端点：/oauth/error
 * 资源服务访问令牌解析端点：/oauth/check_token
 * 提供公有密匙的端点：/oauth/token_key
 */
@Configuration
public class Oauth2Configuration {

    @Configuration
    @EnableAuthorizationServer
    protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter{
        @Autowired
        private DataSource dataSource;
        @Autowired
        private CustomUserDetailsService customUserDetailsService;

        @Bean
        public TokenStore tokenStore(){
            return new JdbcTokenStore(dataSource);
        }

        @Autowired
        @Qualifier("authenticationManagerBean")
        private AuthenticationManager authenticationManager;

        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints){
            endpoints.tokenStore(tokenStore())
                    .authenticationManager(authenticationManager)
                    .userDetailsService(customUserDetailsService)
                    .allowedTokenEndpointRequestMethods(HttpMethod.GET,HttpMethod.POST);
        }

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            clients.jdbc(dataSource);
        }

        @Override
        public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
            security.allowFormAuthenticationForClients();
            security.checkTokenAccess("permitAll()");
        }
    }

}
